<template>
	<div>
		<el-upload
			ref="uploadRef"
			action="#"
			:class="{ hide: state.fileListInner.length >= attrs.limit }"
			:file-list="state.fileListInner"
			:disabled="disabled"
			:list-type="attrs.listType"
			:auto-upload="false"
			:limit="attrs.limit"
			:drag="attrs.drag"
			:before-upload="beforeUpload"
			:on-remove="handleRemove"
			:on-preview="handlePreview"
			:on-exceed="handleExceed"
			:on-change="handleChanged"
			:http-request="uploadRequest"
			:accept="accept"
		>
			<i class="el-icon-plus" v-if="showPlusIcon" />
			<slot />
			<template #trigger v-if="inputType === '9' || (inputType === '7' && attrs.listType === 'picture-card' && attrs.type === '2')">
				<video :src="file.url" controls height="148px" width="148px"></video>
				<span v-if="!props.disabled" class="upload-delete" @click="handleRemove(state.file)">
					<i class="el-icon-delete"></i>
				</span>
			</template>
		</el-upload>
		<el-progress v-if="progress" :percentage="progressPercent" />

		<el-dialog v-if="props.fileList.length" v-model:visible="dialogVisible" append-to-body size="tiny">
			<img :src="dialogImageUrl" width="100%" alt />
		</el-dialog>

		<!-- 剪切组件，暂未加 -->
		<!-- <cropper :imgurl="imgurl" @cropperClone="cropperClone" :config="attrs.cropperCfg"></cropper> -->
	</div>
</template>
<script lang="ts" setup>
import FileIns from './FileClientApi/file_instance.js';
import { getGUID } from './FileClientApi/guid.js';
import { ElMessage, UploadInstance } from 'element-plus';

const props = withDefaults(
	defineProps<{
		attrs: { [x: string]: any };
		disabled: boolean;
		autoUpload: boolean;
		inputType: string;
		fileList: string[];
		postData?: { [x: string]: any };
		setting: { [x: string]: any };
		showPlusIcon: boolean;
		accept?: string;
	}>(),
	{
		attrs: () => {
			return { listType: 'text', limit: 5, drag: true, type: 'img', Bucket: '' };
		},
		disabled: false,
		autoUpload: false,
		setting: () => {
			return { Bucket: '', Region: '' };
		},
		showPlusIcon: true,
		fileList: () => {
			return [];
		},
		accept: '*',
	}
);
const emits = defineEmits(['onChangeFileList']);
const { proxy } = <any>getCurrentInstance();
const uploadRef = ref<UploadInstance>();
watch(
	() => props.fileList,
	() => {
		initFileList();
	}
);

onBeforeMount(async () => {
	if (props.attrs.Bucket) {
		state.fileClient = await FileIns.instance(props.attrs, true);
	} else {
		state.fileClient = await FileIns.instance(props.attrs);
	}
	initFileList();
});
const state = reactive(<any>{
	fileListInner: [],
	deleteList: [],
	dialogImageUrl: '',
	dialogVisible: false,
	key: getGUID(),
	length: 0,
	file: null,
	fileClient: null,
});

const progress = ref(false);
const progressPercent = ref(0);
const fileConfig = ref();
if (localStorage.getItem('setting')) {
	fileConfig.value = JSON.parse(localStorage.getItem('setting') as string);
}

const initFileList = () => {
	state.fileListInner.splice(0, state.fileListInner.length);
	if (props.fileList) {
		for (let i = 0; i < props.fileList.length; i++) {
			console.log('---------------url', props.fileList[i]);
			if (!props.fileList[i].url) {
				console.log('[Debug][File]The file is invalid, url undefined: ', props.fileList[i]);
				continue;
			}
			let url = props.fileList[i].url;
			if (!props.fileList[i].url.startsWith('http')) {
				url = fileConfig.value.ImagUrl + props.fileList[i].url;
			}
			const item = { uid: i, name: props.fileList[i].name || props.fileList[i].url, url: url };
			state.fileListInner.push(item);
		}
	}
};

// eslint-disable-next-line no-unused-vars
const uploadSubmit = async () => {
	console.log('[Debug][File][uploadSubmit]: ', state.fileListInner, state.deleteList);
	let item = {};
	const resList: { name: string; url: string }[] = [];
	let url = '';
	if (fileConfig.value.FtpType !== 0) {
		progress.value = true;
	}
	for (let i = 0; i < state.fileListInner.length; i++) {
		if (!state.fileListInner[i].raw) {
			// 已经上传了的文件，不再上传
			item = { name: state.fileListInner[i].name, url: state.fileListInner[i].url };
			resList.push(item);
			continue;
		}

		url = await state.fileClient.uploadContent(state.fileListInner[i].name, state.fileListInner[i].raw, proxy);

		if (url === null) {
			console.error('[Error][File]upload file fail: ', state.fileListInner[i]);
			continue;
		}

		item = { name: state.fileListInner[i].name, url: url };
		resList.push(item);
	}

	for (let i = 0; i < state.deleteList.length; i++) {
		if (fileConfig.value.FtpType === 3) {
			state.fileClient.deleteFile(state.deleteList[i]);
		} else {
			state.fileClient.deleteFile(state.deleteList[i].url);
		}
	}
	return resList;
};

// eslint-disable-next-line no-unused-vars
const directUpload = async (fileName: string, file: any) => {
	const fileurl = await state.fileClient.uploadContent(fileName, file);
	return fileurl;
};

const onSuccess = (file: any, fileList: any) => {
	console.log('[Debug][File][Upload]success: ', file, fileList);
};

const onError = () => {
	ElMessage({
		message: '上传图片失败!',
		type: 'error',
		// duration: BASE_API.MSG_SHOW_TIME,
	});
};

const uploadRequest = async (file: any) => {
	console.log('dddddddddddddd uploadRequest: ', file);
	const fileUrl = (FileIns.instance() as any).uploadFile();
	if (fileUrl === null) {
		onError();
		return;
	}
	state.fileListInner.push(fileUrl);
	onSuccess(fileUrl, state.fileListInner);
};
// let imgurl = ref();
// let showCropper = ref();
const handleChanged = async (file: any, fileList: any) => {
	console.log('filefile', file);
	// if (props.attrs.cropperCfg && props.attrs.cropperCfg.isCrop) {
	// 	imgurl = file.url;
	// 	showCropper = true;

	// }
	console.log('handleChanged fileList', fileList);
	state.fileListInner = fileList;
	emits('onChangeFileList', file);
	console.log('dddddddddddd: ', state.fileListInner);
	getDuration();
};

const getDuration = () => {
	nextTick(() => {
		setTimeout(() => {
			const video = document.getElementsByTagName('video');
			state.videoArr = [];
			if (video && video.length) {
				for (let i = 0; i < video.length; i++) {
					// video.forEach((item: any, i: number) => {
					state.videoArr.push({
						name: state.fileListInner[i].name,
						duration: video[i].duration,
					});
				}
			}
			console.log('vvvvvvvvvvvvvvvvvvvv', video, state.videoArr);
		}, 500);
	});
};

const beforeUpload = (file: any) => {
	console.log('[Debug][File][beforeUpload]file: ', file);
	state.length++;
	if (state.type === 'text') return true;
	state.key = getGUID();
	const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
	const isLt2M = file.size / 1024 / 1024 < 5;
	if (!isJPG) {
		ElMessage({
			message: '上传图片只能是 JPG/PNG 格式!',
			type: 'error',
			// duration: BASE_API.MSG_SHOW_TIME,
		});
		return false;
	}
	if (!isLt2M) {
		ElMessage({
			message: '上传头像图片大小不能超过 5MB!',
			type: 'error',
			// duration: BASE_API.MSG_SHOW_TIME,
		});
		return false;
	}
	if (isJPG && isLt2M) {
		return true;
	}
};

const handleRemove = (file: any) => {
	console.log('[Debug][File][handleRemove]file: ', file);
	if (file.url) {
		state.deleteList.push(file);
		for (let i = 0; i < state.fileListInner.length; i++) {
			if (state.fileListInner[i].url === file.url) {
				state.fileListInner.splice(i);
				break;
			}
		}
	}
};

const handlePreview = (file: any) => {
	console.log('[Debug][File][handlePreview]file: ', file);
	state.dialogImageUrl = file.url;
	state.dialogVisible = true;
};

const handleExceed = () => {
	ElMessage({
		message: '上传图片数量超过上限',
		type: 'error',
		// duration: BASE_API.MSG_SHOW_TIME,
	});
};

// eslint-disable-next-line no-unused-vars
const cropperClone = (img: any) => {
	// console.log('imgimgimg', img)
	let { ctx } = getCurrentInstance() as any;
	state.fileListInner[state.fileListInner.length - 1].size = img.size;
	state.fileListInner[state.fileListInner.length - 1].url = img.url;
	state.fileListInner[state.fileListInner.length - 1].raw = img.raw;
	// console.log('this.fileListInner', this.fileListInner)
	state.endCropper = true;
	state.showCropper = false;
	ctx.$nextTick(() => {
		state.endCropper = false;
	});
};

const fileListInnerClear = () => {
	state.fileListInner = [];
};
defineExpose({
	uploadSubmit,
	directUpload,
	fileListInnerClear,
});
</script>

<style>
.upload-delete {
	color: red;
	display: block;
	position: absolute;
	top: -6px;
	right: 6px;
	cursor: pointer;
	font-size: 20px;
}
</style>
